# This file contains:
# -  Definition of the class Commit used to store in the couchdb's database

from couchdbkit import *
from time import *
from datetime import *

class Commit(Document):
    date = DateTimeProperty()
    author = StringProperty()
    committer = StringProperty()
    logMessage = StringProperty()
    revision = StringProperty()
    changes = {}
    projectName = StringProperty()
    
    def createCommit(self, date, author, committer, logMessage, revision, changes, name):
        #create a commit object given the parameters
        self.date = datetime.fromtimestamp(mktime(gmtime(date)))
        if type(author) is str:
            self.author = unicode(author, errors='replace')
        else:
            self.author = unicode(author)
        if type(author) is str:    
            self.committer = unicode(committer, errors='replace')
        else:
            self.committer = unicode(committer)
        if self.logMessage is str:
            self.logMessage = unicode(logMessage, errors='replace')
        else:
            self.logMessage = unicode(logMessage)
        self.revision = revision
        self.changes = changes 
        self.projectName = name
        
        self._id = str(self.revision)
        
    def commitToDatabase(self, server, database):
        # save the current commit to the given server and database
        Commit.set_db(database)
        try:
            self.save()
            return True
        except ResourceConflict:
            return False